// ParticleManager.java
package game;

import java.awt.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ParticleManager {
    private CopyOnWriteArrayList<Particle> particles = new CopyOnWriteArrayList<>();
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private boolean isActive = true;
    private GamePanel gamePanel;

    public ParticleManager(GamePanel gamePanel) {
        this.gamePanel = gamePanel;
        startUpdateThread();
    }

    /*
     * 启动粒子更新线程
     */
    private void startUpdateThread() {
        executorService.submit(() -> {
            try {
                while (isActive) {
                    Thread.sleep(16);
                    updateParticles();
                    gamePanel.repaint();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    /*
     * 更新粒子状态
     */
    private void updateParticles() {
        particles.forEach(Particle::update);
        particles.removeIf(p -> p.alpha <= 0);
    }

    /*
     * 创建粒子效果
     */
    public void createParticles(int x, int y, String fruitSymbol) {
        float hue = getHueByFruitSymbol(fruitSymbol);

        for (int i = 0; i < 15; i++) {
            float angle = (float) (Math.random() * Math.PI * 2);
            float speed = (float) (Math.random() * 3 + 1);
            float vx = (float) (Math.cos(angle) * speed);
            float vy = (float) (Math.sin(angle) * speed) - 3;

            float particleHue = hue + (float) (Math.random() * 20 - 10);
            if (particleHue < 0) particleHue += 360;
            if (particleHue > 360) particleHue -= 360;

            particles.add(new Particle(x, y, vx, vy, (int)particleHue, 255));
        }
    }

    private float getHueByFruitSymbol(String fruitSymbol) {
        switch (fruitSymbol) {
            case "🍎": return 0; // 红色
            case "🍌": return 60; // 黄色
            case "🍒": return 340; // 深红色
            case "🍓": return 350; // 草莓红
            case "🍇": return 270; // 紫色
            case "🍊": return 30; // 橙色
            case "🍉": return 120; // 绿色(西瓜皮)和红色(西瓜瓤)
            case "🥝": return 120; // 绿色
            case "🍍": return 60; // 黄色
            default: return 0;
        }
    }

    public void drawParticles(Graphics g) {
        particles.forEach(p -> p.draw(g));
    }

    public void stop() {
        isActive = false;
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }
}